<?php

class Admin_AreaacademicaController extends Zend_Controller_Action {

    private $_operation;
    private $_errorMessages;
    private $_errorLog;
    private $_successMessages;
    private $_deleteAction;

    public function registerAction() {
        $this->_helper->viewRenderer->setNoRender(true);
        $this->_helper->layout->disableLayout();
        $id = $this->getParam('id');
        $account = new VirtualLabs_Rest_VirtualLabs_RegisterUser();
        Zend_Debug::dump($account->registerUserKeys($id));
    }

    public function init() {    
        $this->_operation = $this->_getParam("op");
        $this->_errorMessages = Zend_Registry::get(VirtualLabs_Common::ERROR_MESSAGES);
        $this->_successMessages = Zend_Registry::get(VirtualLabs_Common::SUCCESS_MESSAGES);
        $default = Zend_Registry::get(VirtualLabs_Common::DEFAULT_MESSAGES);
        $this->view->deleteConfirmMessage = $default->delete_confirm_message;
        $this->_errorLog = Zend_Registry::get(VirtualLabs_Common::ERROR_LOG);
    }
    
    public function preDispatch() {
        // Autenticacion del usuario
        $auth = Zend_Auth::getInstance();
        if (!$auth->hasIdentity()) {
            $this->_helper->layout->disableLayout();
            $this->_forward("index", "index", "");
        } else {
            $identity = $auth->getIdentity();
            if ($identity['tipo_usuario'] != VirtualLabs_Admin_Usuario::ROL_ADMIN) {
                $this->_helper->layout->disableLayout();
                $this->_redirect('/');
            }
        }
        //fin de la autenicacion del usuario
    }

    public function indexAction() {
         if ($this->getRequest()->getActionKey() == "delete") {
            echo Zend_Json_Encoder::encode(array("tipo" => "success", "mensaje" => $this->_successMessages->delete));
            $this->view->deleteMessage = $this->_successMessages->delete;
        }
    }

    public function saveAction() {
        $this->_helper->viewRenderer->setNoRender(true);
        $this->_helper->layout->disableLayout();
        $codigo_area_academica = $this->getRequest()->getParam("codigo_area_academica");

        $form = new Admin_Form_AreaAcademica();
        $form->populate($_POST);
        if ($form->isValid($_POST)) {
            $area = new Application_Model_AreaAcademica();
            if ($codigo_area_academica) {
                // success!
                $area_db = $area->find($codigo_area_academica);
                $area_db->setNombre($form->getValue('nombre'));
                $area_db->setDescripcion($form->getValue('descripcion'));

                if ($area_db->save()) {
                    $this->_forward('index');
                } else {
                    $error_message = Zend_Registry::get(VirtualLabs_Common::ERROR_MESSAGES);
                    echo Zend_Json_Encoder::encode($error_message->insert_error);
                }
            } else {
                $area->setNombre($this->getParam('nombre'));
                $area->setDescripcion($this->getParam('descripcion'));
                $area->setPassword(md5($this->getParam('password')));
                $area->setUsernameAccount($this->getParam('username_account'));
                $usuario = new Application_Model_Usuario();
                $usuario_model = $usuario->find($this->getParam('username'));
                $area->setUsuario($usuario_model);

                if ($area->save()) {
                    $account = new VirtualLabs_Rest_VirtualLabs_Account();
                    $accountResponse = $account->createAccount($usuario_model, $form->getValue('username_account'), $form->getValue('password'));
                    $area->setApiKey($accountResponse['register']['registeruserkeysresponse']['userkeys']['apikey']);
                    $area->setSecretKey($accountResponse['register']['registeruserkeysresponse']['userkeys']['secretkey']);
                    $area->setAccountId($accountResponse['createaccountresponse']['account']['id']);

                    if ($area->save()) {
                        $this->_forward('index');
                    } else {
                        $error_message = Zend_Registry::get(VirtualLabs_Common::ERROR_MESSAGES);
                        echo Zend_Json_Encoder::encode($error_message->insert_error);
                    }
                } else {
                    $error_message = Zend_Registry::get(VirtualLabs_Common::ERROR_MESSAGES);
                    echo Zend_Json_Encoder::encode($error_message->insert_error);
                }
            }
        } else {
            echo Zend_Json_Encoder::encode($form->getErrors());
        }
    }

    public function editAction() {
        $area_academica = new Application_Model_AreaAcademica();
        $area_db = $area_academica->find($this->getRequest()->getParam("id"));
        $form = new Admin_Form_AreaAcademica();
        $form->populate($area_db->toArray());
        $this->view->form = $form;
    }

    public function viewAction() {
        $this->_deleteAction = true;
        $this->_helper->viewRenderer->setNoRender(true);
        $area_academica = new Application_Model_AreaAcademica();
        $area_db = $area_academica->find($this->getRequest()->getParam("id"));
        print_r($area_db->toArray());
    }

    public function listAction() {
        $this->_helper->viewRenderer->setNoRender(true);
        $this->_helper->layout->disableLayout();

        $area_academica = new Application_Model_AreaAcademica();
        $list = $area_academica->fetchList();
        $response = array();
        foreach ($list as $a) {
            $row = $a->toArray();
            $response [] = array($this->view->deleteUrl($row['codigo_area_academica'], "areaacademica"), $this->view->editUrl($row['codigo_area_academica'], $row['nombre'], "areaacademica"),
                $row['descripcion']);
        }
        echo Zend_Json_Encoder::encode($response);
    }

    public function deleteAction() {
        $this->_deleteAction = true;
        $this->_helper->viewRenderer->setNoRender(true);
        $this->_helper->layout->disableLayout();
        $codigo_area_academica = $this->getRequest()->getParam("id");
        if (isset($codigo_area_academica)) {
            $area_academica = new Application_Model_AreaAcademica();
            $area_db = $area_academica->find($codigo_area_academica);
            $area_mapper = new Application_Model_Mapper_AreaAcademica();
            $this->_errorLog->debug("codigo de cuenta : " . $area_db->getAccountId());
            try {
                $account = new VirtualLabs_Rest_VirtualLabs_Account();
                $account->deleteAccount($area_db->getAccountId());
                $area_mapper->delete($area_db);
                $this->_forward('index');
            } catch (Exception $e) {
                $this->_errorLog->err($e->getMessage());
                $this->_errorLog->err($e->getTraceAsString());
                echo Zend_Json_Encoder::encode(array("tipo" => "error", "mensaje" => $this->_errorMessages->completar_operacion));
            }
        } else {
//            echo Zend_Json_Encoder::encode(array("tipo" => "error", "mensaje" => $this->_errorMessages->completar_operacion));
        }
    }

}

